const path = require('path');
const express = require('express');
const apiRouter = require('./apiRoute');

const app = express();

// 获取端口号
const port = process.argv.length > 2 ? parseInt(process.argv[2]) : 8080;

const dir = '../assets/dist';
const __DEV__ = process.env.NODE_ENV == 'dev';

// 仅在开发模式下使用热加载插件
if (__DEV__) {
	const webpack = require('webpack');
	const config = require('../webpack.config.dev');
	const compiler = webpack(config);

	app.use(require('webpack-dev-middleware')(compiler, {
		noInfo: true,
		publicPath: config.output.publicPath
	}));

	app.use(require('webpack-hot-middleware')(compiler));
}

// 设置静态目录
app.use('/static', express.static(path.join(__dirname, dir)));

// 返回承载页
app.use('/app', (req, res, next) => {
	res.sendFile(path.join(__dirname, dir, 'app.html'));
});

// 添加/api/* 路由
app.use('/api', apiRouter);

// 打开监听
app.listen(port, 'localhost', (err) => {
	if (err) {
		return console.log(err);;
	}

	console.log(`Listening at http://localhost:${port}`);
});